package com.edoomath.api.handler.impl;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.demo2do.core.http.annotation.Rao;
import com.demo2do.core.utils.DateFormatUtils;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.utils.StringUtils;
import com.edoomath.api.WeappNoticeTemplate;
import com.edoomath.api.handler.WeappNoticeHandler;
import com.edoomath.api.rao.WeappNoticeRao;
import com.edoomath.entity.user.WeappNoticeTicket;
import com.edoomath.entity.user.WechatOpenid;
import com.edoomath.entity.usercourse.UserCourseTask;

/**
 * 
 * @author mohanlan
 *
 */
@Component("weappNoticeHandler")
public class WeappNoticeHandlerImpl implements WeappNoticeHandler {
	
	@Value("#{config['tencent.host']}")
    private String tencentHost;
	
	@Rao
	private WeappNoticeRao weappNoticeRao;
	
	private static final Logger logger = LoggerFactory.getLogger(WeappNoticeHandler.class);

	/*
	 * (non-Javadoc)
	 * @see com.edoomath.api.handler.WeappNoticeHandler#taskSigninNotice(com.edoomath.entity.user.WechatOpenid, com.edoomath.entity.usercourse.UserCourseTask)
	 */
	public void taskSigninNotice(String page, WechatOpenid wechatOpenid, UserCourseTask userCourseTask) {
		
		try {
			// 1. load weapp notice ticket here
			WeappNoticeTicket ticket = this.getTaskSinginWeappNoticeTicket(userCourseTask);
			
			// 2. do send notice
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("openid", wechatOpenid.getOpenid());
			params.put("template_id", WeappNoticeTemplate.TASK_SIGNIN_NOTICE);
			params.put("form_id", ticket.getValue());
			
			if(org.apache.commons.lang3.StringUtils.isNotBlank(page)) {
				params.put("page", page);
			}
			
			Map<String, String> datas = new LinkedHashMap<String, String>();
			datas.put("keyword1", userCourseTask.getUserCourse().getCourse().getName());
			datas.put("keyword2", userCourseTask.getMaterail().getName());
			datas.put("keyword3", DateFormatUtils.format(userCourseTask.getFinishTime(), "yyyy-MM-dd HH:mm:SS"));
			datas.put("keyword4", "审核通过");
			datas.put("keyword5", "陆老师");
			datas.put("keyword6", userCourseTask.getComment());
			datas.put("keyword7", "小心，您该行动起来了~");
			
			params.put("datas", datas);
			
			String url = StringUtils.connect(tencentHost, "/weapp/notice/send");
			
			logger.info("start call send weapp notice with url [{}] params [{}]", url, JsonUtils.toJson(params));
			weappNoticeRao.send(url, params);
			
			// 3. change ticket to used here
			
		} catch (Exception e) {
			logger.error("send weapp notice occurs error : ", e);
		}
	}
	
	/**
	 * 
	 * @param userCourseTask
	 * @return
	 */
	private WeappNoticeTicket getTaskSinginWeappNoticeTicket(UserCourseTask userCourseTask) {
		
		// TODO load WeappNoticeTicket here
		
		return null;
	}
	
}
